package com.cjk.foundation.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.security.SecureRandom;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	private static final SecureRandom random = new SecureRandom();

	public static String getRandomFileName(final String extention) {
		final String time = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS");
		final String rand = Long.toHexString(random.nextLong());
		return time + rand + "." + extention;
	}
	
	public static void storeFile(MultipartFile file, String dir, String fileName) {
		
		File directory = new File(dir);
		if (!directory.exists()) {
			directory.mkdirs();
			if (!directory.exists()) {
				throw new IllegalStateException("无法创建广告上传存储目录");
			}
		}
		
		directory = directory.getAbsoluteFile();
		
		File storeFile = new File(directory, fileName);
		
		try {
			IOUtils.copy(file.getInputStream(), new FileOutputStream(storeFile));
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		
	}
	
	public static void writeFile(String dirPath, String fileName, String content) {
		try {
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			
			File file = new File(dirPath + fileName);
			file.createNewFile();
			
			Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			write.write(content);
			write.flush();
			write.close();
		} catch (Exception e) {
			logger.error("文件[{}]写入失败 : {}", fileName, e.getMessage());
		}
	}
	
}